package com.woniuxy.predicate;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @Author WY
 * @PackageName phase-iv-cyx
 * @Package com.woniuxy.predicate
 * @Date 2022/12/8 17:34
 * @Version 1.0
 */
@Component
public class PidNumlimitRoutePredicateFactory extends AbstractRoutePredicateFactory<PidNumlimitRoutePredicateFactory.Config> {
    public PidNumlimitRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("minPid","maxPid","maxNum");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                String path = serverWebExchange.getRequest().getURI().getPath();
                String[] split = path.split("/");
                String pidString = split[split.length - 2];
                String numString = split[split.length - 1];
                int pid = Integer.parseInt(pidString);
                int num = Integer.parseInt(numString);
                if (pid>=config.getMinPid()&&pid<=config.getMaxPid()&&num>= config.getMinPid()&&num<= config.getMaxNum()){
                    return true;
                }else {
                    return false;
                }

            }
        };
    }


    public static class Config{
        int minPid;
        int maxPid;
        //int minNum;
        int maxNum;

        public int getMinPid() {
            return minPid;
        }

        public void setMinPid(int minPid) {
            this.minPid = minPid;
        }

        public int getMaxPid() {
            return maxPid;
        }

        public void setMaxPid(int maxPid) {
            this.maxPid = maxPid;
        }



        public int getMaxNum() {
            return maxNum;
        }

        public void setMaxNum(int maxNum) {
            this.maxNum = maxNum;
        }
    }
}
